package com.cicadasmall.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
public class DbUtils {


    private final DataSource dataSource;

    private DbUtils(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public static DbUtils use(DataSource dataSource) {
        return new DbUtils(dataSource);
    }

    public boolean exec(String sql) {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            return stmt.execute(sql);
        } catch (SQLException e) {
            log.error("sql 执行失败！ -{}", e);
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("connection 关闭失败！ -{}", e);
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    log.error("statement 关闭失败！ -{}", e);
                }
            }
        }
    }

}
